<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/10/17
 * Time: 上午9:42
 */

namespace app\index\controller;


use app\common\controller\ActionLogs;
use app\common\controller\AfterPayPutCard;
use app\common\controller\Balance;
use app\common\controller\Bonus;
use app\common\controller\CardDedu;
use app\common\controller\CardMarke;
use app\common\controller\CardPut;
use app\common\controller\CardPuttest;
use app\common\controller\CreateNotify;
use app\common\controller\Deviceobj;
use app\common\controller\FeiePrint;
use app\common\controller\Fenzhang;
use app\common\controller\Fztest;
use app\common\controller\Payinfo;
use app\common\controller\Platurl;
use app\common\controller\TemplateMsg;
use app\common\controller\UserBonusFee;
use app\common\controller\Ydhwork;
use app\common\model\Agent;
use app\common\model\CardBonusRule;
use app\common\model\CardConsume;
use app\common\model\CardCzgive;
use app\common\model\CardCzLog;
use app\common\model\CardGeneral;
use app\common\model\CardGivecardLog;
use app\common\model\CardJcList;
use app\common\model\CardJcLog;
use app\common\model\CardJcUserget;
use app\common\model\CardMember;
use app\common\model\CardPaycardlog;
use app\common\model\CardRank;
use app\common\model\CardUserGet;
use app\common\model\CardUserLog;
use app\common\model\CardUserRecLog;
use app\common\model\CardUserUpdate;
use app\common\model\Merchant;
use app\common\model\OpenTemplate;
use app\common\model\Paylog;
use app\common\model\PaymentCardPut;
use app\common\model\PaymentCardPutLog;
use app\common\model\ProfitList;
use app\common\model\System;
use app\common\model\WxOpen;
use app\common\model\WxUser;

use app\common\model\YdhOpen;
use app\common\model\YdhUser;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;
use Wnkj\WnCardObj;

class Wxpayextend extends PayBase
{



    //支付后送券
    /*
     *  orderid  openid  mid  price add_time
     * */
    public function payment_card_put($param)
    {
        try {
            //判断是否微信支付
            if ($param['pay_fs'] == 0 || $param['pay_fs'] == 2) {
                $AfterPayPutCard = new AfterPayPutCard();
                $arrc = $AfterPayPutCard->paymentcard($param);
            } else {
                $arrc = 'error1';
            }
        } catch (\Exception $e) {
            $arrc = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
            $ActionLogs = new ActionLogs();
            $ActionLogs->writelog("payos","payment","paycards","1:",$arrc);

        }
        return $arrc;
    }

    public function paycardus($arr)
    {

        try {
            $CardUserGet = new CardUserGet();
            $CardPaycardlog = new CardPaycardlog();
            $paycardus = $CardPaycardlog->where(['orderid' => $arr['orderid']])->field('openid,user_code,putstatu')->find();
            //等于1 则结束
            if ($paycardus['putstatu'] == 1) {
                exit();
            };
            $user = $CardUserGet->where(['code' => $paycardus['user_code'], 'openid' => $paycardus['openid']])->field('openid,code,card_id')->find();
            $CardPaycardlog->allowField(true)->save(['paystatu' => 1, 'paytime' => time()], ['orderid' => $arr['orderid']]);
            if ($user) {
                $data['membership_number'] = $paycardus['user_code'];
                $data['code'] = $paycardus['user_code'];
                $data['card_id'] = $user['card_id'];
                $data['openid'] = $user['openid'];
                $CardMarke = new CardMarke();
                $res = $CardMarke->activcardus($data);
                if ($res['errcode'] == 0) {
                    $CardPaycardlog->allowField(true)->save(['putstatu' => 1], ['orderid' => $arr['orderid']]);
                }
            } else {
                $res = '';
            }
            return $res;
        } catch (\Exception $e) {
            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
        }
        return $res;
    }




    //根据card_id获取Mid
    public function getmid($card_id)
    {
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id' => $card_id])->value('mid');
        if (empty($top_mid)) {
            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('mid');
            return $top_mid;
        } else {
            return $top_mid;
        }
    }

    //Ajax打开领取
    /*
     * top_mid  rec_id openid
     */
    public function getpaymentcard($param)
    {
//        return json($param);
        $CardGivecardLog = new CardGivecardLog();
        $cardlist = $CardGivecardLog->where(['top_mid' => $param['top_mid'], 'give_rec_id' => $param['rec_id'], 'put_type' => 'payment_card'])->select();
        $card = [];
        foreach ($cardlist as $k => $v) {
            $outer_str = 'giveRecId_' . $v['id'];
            $isgetput = $this->isgetputsume($v['zs_card_id'], $outer_str, $param['openid'], $v['put_sume']);
            if ($v['put_sume'] > $v['get_sume'] && $isgetput == 0) {
                for ($x = 0; $x < $v['put_sume']; $x++) {
                    $arrs['card_id'] = $v['zs_card_id'];
                    $arrs['openid'] = $param['openid'];
                    $arrs['outer_str'] = 'giveRecId_' . $v['id'];
                    $card[] = $this->putlist($arrs);
                }
            }
        }
        return $card;

    }

    //判断领取数量是否达到发放数量
    private function isgetputsume($card_id, $outerstr, $openid, $put_sume)
    {
        try {
            $CardUserGet = new CardUserGet();
            $map['card_id'] = $card_id;
            $map['outerstr'] = $outerstr;
            $map['openid'] = $openid;
            $get_sume = $CardUserGet->where($map)->count('id');
            if ($put_sume < $get_sume || $put_sume == $get_sume) {
                return 1;
            } else {
                return 0;
            }
        } catch (\Exception $e) {
            return 0;
        }
    }

    //批量投放
    /*
     * $arr['openid'] / $arr['card_id']
     */
    private function putlist($arr)
    {
        $options = $this->options($arr['card_id']);
        $weObj = new Wxobjopen($options);
        $noncestr = $weObj->generateNonceStr();
        $outer_str = $arr['outer_str'];
        $res['cardId'] = $arr['card_id'];
        $res['cardExt'] = $weObj->wxAddCard($arr['openid'], $arr['card_id'], $noncestr, $outer_str);
        return $res;
    }

    public function orderinfo_query(Request $request){
        if ($request->isAjax()){
            $param = $request->post();
            $PaymentCardPutLog = new PaymentCardPutLog();
            $map['orderid'] = $param['orderid'];
//            $map['openid'] = Session::get('openid');
            $payinfo = $PaymentCardPutLog->where($map)->find();
            if ($payinfo){
                $Merchant = new Merchant();
                $top_mid = $Merchant->where(['id'=>$payinfo['mid']])->value('top_mid');
                $params1['top_mid'] = $top_mid;
                $params1['openid'] = session('openid');
                $params1['rec_id'] = $payinfo['id'];

                $cards = $this->getpaymentcard($params1);
                $re_data['return_code'] = "SUCCESS";
                $re_data['return_msg'] = "成功";
                $re_data['data']['item'] = $cards;
            }else{
                $re_data['return_code'] = "FAIL";
                $re_data['return_msg'] = "无送券";
            }
            return json($re_data);
        }
    }



    public function getorder2()
    {
        $request = request();
        if ($request->isAjax()) {
            $sh = $request->post('id');
            $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
            echo $order;
        }
    }

    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        //  Session::set('openid', null);
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $mid = $CardMember->where('card_id', $card_id)->value('mid');
        if ($mid) {
            $map['id'] = $mid;
        } else {
            $map['id'] = $CardGeneral->where('card_id', $card_id)->value('mid');
        }
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

}